<template>
  <div class="testSession">
    <componentsHeader></componentsHeader>
    <div class="main">
      <el-row>
        <el-col>
          <p>
            <!--            2020年首届“中德安普杯”全国职业院校(高职组)业财税融合暨大数据管理会计应用能力大赛-->
            {{taskName}}
          </p>
          <!--          <p>-->
          <!--            -->
          <!--          </p>-->
        </el-col>
      </el-row>
      <el-row>
        <div class="testItem" v-for="(testItem,index) in testList" :key="testItem.matchName"
          :class="testItem.status == 1?'start':testItem.status == 2?'end':'noStart'" @click="checkRoom(testItem,index)">
          <div class="wrap">
            <div class="timeWrap" v-if="testItem.status === 0">
              {{timeTrans(testItem.startTime,testItem.endTime)}}
            </div>
            <div class="timeWrap" v-html="testItem.countDown" v-if="testItem.status === 1"></div>
            <!--          <div class="timeWrap" v-if="testItem.Status === 2">-->
            <!--            <i>倒计时：</i>-->
            <!--            <span>00</span>时-->
            <!--            <span>00</span>分-->
            <!--            <span>00</span>秒-->
            <!--          </div>-->
            <div class="testItemMain">
              <!--            <div>-->
              <p>{{testItem.name}}</p>
              <p>{{testItem.matchName}}</p>
              <!--            </div>-->
            </div>
          </div>
        </div>
      </el-row>
    </div>
    <div class="footer">
      <p>&copy;专一网 湖南中德安普大数据网络科技有限公司</p>
      <p>
        <!-- <a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=737158116&site=qq&menu=yes">在线客服</a>
        <span>|</span>
        <a @click="showImg = true">商务联系</a> -->
      </p>
      <div v-show="showImg">
        <img src="/static/img/student/phone.png" alt />
        <!-- <img src="@/assets/phone2.png" alt="" v-show='phoneImg == 2'> -->
        <i class="el-icon-close" @click="showImg = false"></i>
        <el-button size="mini" @click="showImg = false">确定</el-button>
      </div>
    </div>
    <el-dialog title="提示" :visible.sync="showSubmitTrue" :close-on-click-modal='false' width="30%"
      class="submitSuccess">
      <span>{{numTime}}s后自动进入考试</span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    mapGetters
  } from "vuex";
  import componentsHeader from "@/components/header.vue";

  export default {
    components: {
      componentsHeader
    },
    name: "testSession",
    data() {
      return {
        showImg: false,
        taskName: "中德安普测试", //任务名称
        testList: [
          {
            "venuesId": 1293229312693120,
            "examId": 1293228283349607,
            "taskName": "中德安普测试8",
            "name": "上半场",
            "matchName": "竞赛",
            "startTime": "2021-11-11 14:10:00",
            "endTime": "2021-11-11 16:40:00",
            "groupId": 1293228283349613,
            "gradeId": 1293228283349612,
            "postionId": 931254285942814,
            "postionName": "业务会计",
            "caseId": 1085344010719282,
            "totalTime": 150,
            "totalScore": 400,
            "caseYear": "2021",
            "rollUpType": 0,
            "imGroupId": 164848836083715,
            "venuesStatus": "进行中",
            "currentTime": "2021-11-11 14:23:05"
          }
        ],
        times: null, //倒计时
        newData: "", //当前时间
        timesList: [], //倒计时列表
        numTime: null,
        showSubmitTrue: false
      };
    },
    mounted() {},
    created() {
      this.getproexamlistbytaskidFn();
    },
    beforeDestroy() {
      clearInterval(this.times);
      this.times = null;
    },
    methods: {
      checkRoom(val, ind) {
        this.validateprocompetitiondateFn(val);
      },
      timeTrans(start, end) {
        function addDateZero(num) {
          return (num < 10 ? "0" + num : num);
        }

        let d = new Date(start);
        let t = new Date(end);
        let formatdatetime = addDateZero(d.getMonth() + 1) + '.' + addDateZero(d.getDate()) + ' ' + addDateZero(d
          .getHours()) + ':' + addDateZero(d.getMinutes()) + ':' + addDateZero(d.getSeconds());
        formatdatetime = formatdatetime + '-' + addDateZero(t.getHours()) + ':' + addDateZero(t.getMinutes()) + ':' +
          addDateZero(t.getSeconds())
        // let formatdatetime = d.getFullYear() + '-' + addDateZero(d.getMonth() + 1) + '-' + addDateZero(d.getDate()) + ' ' + addDateZero(d.getHours()) + ':' + addDateZero(d.getMinutes()) + ':' + addDateZero(d.getSeconds());
        return formatdatetime;
      },
      //根据taskId获取考试信息
      getproexamlistbytaskidFn() {
        // this.$api.examProvincialCompetitionTaskService
        //   .getproexamlistbytaskid()
        //   .then(res => {
        //     console.log(res,'根据taskId获取考试信息-test');
        //     if (res.Code == 200) {
        //       res.Data.forEach(val => {
        //         val.Status = val.VenuesStatus == "进行中" ? 1 : val.VenuesStatus == "已结束" ? 2 : 0;
        //         // val.NewDate = val.CurrentTime.split("T")[0].split("-").join("/") + " " + val.CurrentTime.split("T")[1].split(".")[0];
        //         val.NewDate = val.CurrentTime;
        //       });
        //       this.taskName = res.Data[0].TaskName;
        //       this.testList = res.Data;
        //       this.testList.forEach(v => {
        //         if (v.Status == 1) {
        //           this.newData = new Date(v.NewDate).getTime();
        //         }
        //       });
        //       this.setTime();
        //     }
        //   })
        //   .catch(err => {
        //     console.log(err, "err");
        //   });
      },
      //验证是否在考试时间段内
      validateprocompetitiondateFn(val) {
        let params = {
          venuesId: val.VenuesId
        };
        this.$api.examProvincialCompetitionTaskService
          .validateprocompetitiondate(params)
          .then(res => {
            // console.log(res,'验证是否在考试时间段内');
            if (res.Code == 200) {
              if (res.Data) {
                this.numTime = Math.floor(Math.random() * 4);
                // console.log("可以考试了", val);
                this.showSubmitTrue = true;
                var time = setInterval(() => {
                  if (this.numTime == 0) {
                    clearInterval(time);
                    this.showSubmitTrue = false;
                    sessionStorage.setItem("PracticeGradeId", val.GradeId);
                    this.$router.push({
                      path: "/exam",
                      query: {
                        ExamId: val.ExamId,
                        CaseId: val.CaseId,
                        CaseYear: val.CaseYear,
                        Name: val.MatchName,
                        GradeId: val.GradeId,
                        ImGroupId: val.ImGroupId,
                        RollUpType: val.RollUpType,
                        PostionId: val.PostionId,
                        PostionName: val.PostionName,
                        GroupId: val.GroupId,
                      }
                    });
                    return;
                  }
                  this.numTime--
                }, 1000)
              } else {
                this.$notify({
                  title: "提示",
                  type: "info",
                  message: res.Msg
                });
                return;
              }
            }
          })
          .catch(err => {
            console.log(err, "err");
          });

        // 添加查询组成员信息
        this.$api.examProvincialCompetitionTaskService
          .getgroupuserinfobygroupid(val.GroupId).then(res => {
            // console.log(res)
            if (res.Code == 200) {
              sessionStorage.setItem("mygroup", JSON.stringify(res.Data))
            }
          }).catch(err => {
            console.log(err, "err");
          })
      },
      setTime(data) {
        this.testList.forEach(v => {
          if (v.Status == 1) {
            this.$set(v, "countDown", this.showtime(this.newData, v.EndTime));
          }
        });
        this.times = setInterval(() => {
          this.newData = this.newData + 1000;
          //每次定时器列表清空
          this.timesList = [];
          let isClearInterval = true;
          this.testList.forEach(v => {
            if (v.Status == 1) {
              //当有场次是进行中的时候更改变量为false
              isClearInterval = false;
              this.$set(v, "countDown", this.showtime(this.newData, v.EndTime));
            }
          });
          //当场次都是结束状态移除定时器
          if (isClearInterval) {
            clearInterval(this.times);
            this.times = null;
            // this.getproexamlistbytaskidFn();
          }
        }, 1000);
      },
      //时间格式
      timeFormat(lefttime) {
        let lefth = this.tow(Math.floor(lefttime / 60)), //计算小时数
          leftm = this.tow(Math.floor(lefttime % 60)); //计算分钟数
        return `<i>倒计时：</i><span>${lefth}</span>时 <span>${leftm}</span>分 <span>00</span>秒`; //返回倒计时的字符串
      },

      showtime(nowtime, endTime) {
        let endtime = new Date(endTime).getTime(); //定义结束时间
        //当当前时间你小于结束时间，向列表中push一个状态
        if (nowtime < endtime) {
          this.timesList.push(true)
        }
        //当定时器列表为空时说明所有的倒计时都已清0，移除定时器
        if (this.timesList.length < 1) {
          clearInterval(this.times);
          this.times = null;
          this.getproexamlistbytaskidFn();
          return "<i>倒计时：</i><span>00</span>时 <span>00</span>分 <span>00</span>秒"
        } else if (nowtime >= endtime) { //当当前时间大于等于结束时间，表明该任务已结束，返回00:00:00
          return "<i>倒计时：</i><span>00</span>时 <span>00</span>分 <span>00</span>秒"
        }
        // if (nowtime >= endtime) {
        //   // clearInterval(this.times);
        //   // this.times = null;
        //   this.getproexamlistbytaskidFn();
        //   return "<i>倒计时：</i><span>00</span>时 <span>00</span>分 <span>00</span>秒";
        // }
        let lefttime = endtime - nowtime, //距离结束时间的毫秒数
          lefth = this.tow(Math.floor((lefttime / (1000 * 60 * 60)) % 24)), //计算小时数
          leftm = this.tow(Math.floor((lefttime / (1000 * 60)) % 60)), //计算分钟数
          lefts = this.tow(Math.floor((lefttime / 1000) % 60)); //计算秒数
        return `<i>倒计时：</i><span>${lefth}</span>时 <span>${leftm}</span>分 <span>${lefts}</span>秒`; //返回倒计时的字符串
      },
      tow(n) {
        return n >= 0 && n < 10 ? "0" + n : "" + n;
      }
    },
    computed: {
      ...mapGetters({})
    },
    watch: {}
  };
</script>

<style lang="less">
  .testSession {
    height: 100vh;
    min-height: 500px;
    min-width: 1000px;
    width: 100%;
    background: url("/static/img/student/testSessionBg.png") center/cover no-repeat;
    position: relative;

    p {
      margin-bottom: 0;
    }

    .main {
      position: absolute;
      width: 100%;
      top: 45%;
      transform: translateY(-50%);

      .el-row {
        &:nth-of-type(1) {
          width: 630px;
          margin: 0 auto;
          text-align: center;
          font-size: 28px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: rgba(48, 44, 72, 1);
          text-shadow: 2px 2px 2px rgba(13, 43, 128, 0.1);
        }

        &:nth-of-type(2) {
          margin: 64px 0;
          text-align: center;

          .testItem {
            width: 380px;
            height: 180px;
            display: inline-block;
            cursor: pointer;
            vertical-align: top;

            &:nth-of-type(2) {
              margin-left: 40px;
            }

            &.noStart {
              background: url("/static/img/student/campus_notstarted.png") no-repeat;

              .timeWrap {
                /*color: #FF3D33;*/
                color: #0081FF;
                text-align: center;
                line-height: 30px;
                font-size: 16px;
                /*font-weight: 600;*/
              }
            }

            &.start {
              background: url("/static/img/student/campus_start.png") no-repeat;

              .timeWrap {
                color: #fff;

                i {
                  color: #fff;
                }
              }
            }

            &.end {
              background: url("/static/img/student/campus_end.png") no-repeat;
            }

            &.noStart,
            &.end {
              /*.wrap {*/
              /*  width: 100%;*/
              /*  height: 100%;*/
              /*  display: flex;*/
              /*  align-items: center;*/

              /*  .testItemMain {*/
              /*    width: 100%;*/

              /*    p {*/
              /*      &:nth-of-type(1) {*/
              /*        margin-top: 0;*/
              /*      }*/
              /*    }*/
              /*  }*/
              /*}*/
            }

            .timeWrap {
              /*position: absolute;*/
              /*top: 5px;*/
              text-align: right;
              margin-top: 16px;
              font-size: 14px;
              font-family: PingFangHK-Medium, PingFangHK;
              font-weight: 500;
              box-sizing: border-box;
              padding-right: 35px;

              i {
                font-style: normal;
                font-size: 16px;
                font-weight: 500;
              }

              span {
                display: inline-block;
                text-align: center;
                box-sizing: border-box;
                padding-right: 1px;
                width: 28px;
                height: 27px;
                background: linear-gradient(154deg,
                    rgba(255, 135, 2, 1) 0%,
                    rgba(253, 79, 1, 1) 100%);
                border-radius: 4px;
                line-height: 27px;
                font-size: 18px;
                font-family: DINAlternate-Bold, DINAlternate;
                font-weight: bold;
                color: rgba(255, 255, 255, 1);
                margin: 0 5px 0 10px;
              }
            }

            .testItemMain {
              /*height: calc(100% - 40px);*/
              /*display: flex;*/
              /*align-items: center;*/
              /*div{*/
              /*  width: 100%;*/

              p {
                width: 100%;
                text-align: center;

                &:nth-of-type(1) {
                  font-size: 24px;
                  font-family: PingFangSC-Semibold, PingFang SC;
                  font-weight: 600;
                  color: rgba(255, 255, 255, 1);
                  margin-top: 23px;
                }

                &:nth-of-type(2) {
                  font-size: 20px;
                  font-family: PingFangSC-Medium, PingFang SC;
                  font-weight: 500;
                  color: rgba(255, 255, 255, 1);
                  margin-top: 10px;
                }
              }

              /*}*/
            }
          }
        }
      }
    }

    .footer {
      position: absolute;
      bottom: 0;
      width: 100%;
      box-sizing: border-box;
      padding: 0 52px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 60px;
      // background:  #fff;
      line-height: 60px;
      color: #666666;
      font-size: 14px;

      span {
        margin: 0 0.4rem;
      }

      a {
        color: #666666;
        text-decoration: none;
        cursor: pointer;
      }

      div {
        position: absolute;
        right: 5px;
        bottom: 60px;

        img {
          z-index: 100;
          position: relative;
        }

        i {
          position: absolute;
          right: 6px;
          top: 6px;
          z-index: 101;
          color: #fff;
        }

        .el-button {
          position: absolute;
          right: 6px;
          bottom: 4px;
          z-index: 101;
        }
      }
    }

    .submitSuccess {
      .el-dialog {
        margin-top: 36vh !important;
        width: 200px !important;
        height: 75px;
        border-radius: 8px;
        background: rgba(51, 51, 51, 0.8);
        color: #fff;
        text-align: center;

        .el-dialog__header {
          display: none;
        }

        span {
          color: #fff;
        }
      }
    }
  }
</style>
